let express = require('express');
let Router = express.Router();
module.exports = Router;

let query = require('./db');

Router.put('/add/:goods_id',async(req,res)=>{
    let {goods_id}=req.params
    let {user_id}=req.info
    try {
        // 先判断该用户是否有该商品，有则在原有基础上数量加一，否则添加数据
        
        let data=await query(`select * from cart where user_id=${user_id} and goods_id=${goods_id};`)
        let sql=''
        // 没有该商品
        if(data.length==0){
            sql = `insert into cart values(${null},${goods_id},${user_id},1);`
        }else{
            let num = data[0].cart_num * 1 + 1;
            sql = `update cart set cart_num=${num} where user_id=${user_id} and goods_id=${goods_id};`
        }
        await query(sql)
        res.send({
            code:200,
            msg:'添加成功'
        })
    } catch (error) {
        res.send({
            code: 400,
            msg:error
        })
    }

})
// 连表查询
Router.get('/carData',async(req,res)=>{
    let {user_id}=req.info
    try {
        let data=await query(`select * from cart inner join goods on cart.goods_id=goods.goods_id where user_id=${user_id}`)
        res.send({
            code:200,
            msg:'查询成功',
            data
        })
    } catch (error) {
        res.send({
            code:400,
            msg:error,
        })
    }
})
// 删除商品的接口
// 获得商品id 用户id
Router.get('/delGoods/:goods_id',async(req,res)=>{
    let {user_id}=req.info
    let {goods_id}=req.params
    try {
        let data=await query(`select * from cart where user_id=${user_id} and goods_id=${goods_id};`)
        let num=((data[0].cart_num)*1)-1
        await query(`update cart set cart_num=${num} where user_id=${user_id} and goods_id=${goods_id};`)
        console.log(`update cart set cart_num=${num} where user_id=${user_id} and goods_id=${goods_id};`);
        res.send({
            msg:'删减成功！',
            num,
        })
    } catch (error) {
        res.send(error)
    }  
})
// 获取某个商品的数量
Router.get('/getCart_num/:goods_id',async(req,res)=>{
    let {user_id}=req.info
    let {goods_id}=req.params
    try {
        let data=await query(`select * from cart where user_id=${user_id} and goods_id=${goods_id};`)
        let num=((data[0].cart_num)*1)
        
        res.send({
            msg:'查询成功！',
            num,
        })
    } catch (error) {
        res.send(error)
    }  
})
